package com.example.test.controller;

import com.example.test.bean.UserBean;
import com.example.test.bean.UserImgBean;
import com.example.test.log.annotation.LoggerAnnotation;
import com.example.test.log.enums.LogSeverity;
import com.example.test.service.UserService;
import com.example.test.utils.FileUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class UserController {

    @Resource
    UserService userService;

   // @RequestMapping("/users")
    public String showUsers(ModelMap modelMap){
        List<UserBean> userList = userService.getAllUser();
        modelMap.addAttribute("userList",userList);
        return "users";
    }

    @LoggerAnnotation(operSource = "测试用例服务工程",
            severity = LogSeverity.RISK,operName = "22保存用户信息",
            isPersistence = true)
    @RequestMapping("/test-except")
    @ResponseBody
    public String testException() throws Exception{
        throw new RuntimeException("测试异常");
        //return "success";
    }

    @LoggerAnnotation(operSource = "测试用例服务工程",
            severity = LogSeverity.MINOR,
            operName = "保存用户信息",isPersistence = true)
    @RequestMapping("/users")
    public String index(Model model,
                        @RequestParam(defaultValue = "2") Integer pageNum,
                        @RequestParam(defaultValue = "3") Integer pageSize) {
        PageInfo<UserBean> pageInfo = userService.selectUser4Page(pageNum, pageSize);

        //4.使用model传参数回前端
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("userList", pageInfo.getList());

        return "users";
    }

    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    @ResponseBody
    public Map addUser(UserBean userBean, HttpServletRequest request){
        int flag = userService.insertUser(userBean);

        UserImgBean userImgBean = new UserImgBean();
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        for (MultipartFile multipartFile : files) {
            if(multipartFile.isEmpty())
                continue;
            byte[] fileBytes = new byte[0];
            try {
                fileBytes = multipartFile.getBytes();
                String originalFilename = multipartFile.getOriginalFilename();
                originalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + originalFilename;
                boolean bRet =   FileUtils.uploadFile(fileBytes, "static/upload/"+fileName);
                if (bRet == false)
                    continue;

                userImgBean.setId(0);
                userImgBean.setUser_id(userBean.getId());
                userImgBean.setImg("upload/"+fileName);
                int iFlag =  userService.insertUserImg(userImgBean);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Map<String,Object> map = new HashMap<String,Object>();
        if(flag == 1){
            map.put("msg","新增用户成功");
            return map;
        }else {
            map.put("msg","新增用户失败");
            return map;
        }
    }

    @RequestMapping(value = "/deleteUser+{id}")
    public String deleteUser(@PathVariable("id") String id, ModelMap modelMap){
        int flag = userService.deleteUser(id);
        List<UserBean> userList = userService.getAllUser();
        modelMap.addAttribute("userList",userList);
        if(flag == 1){
            return "users";
        }else {
            return "error";
        }
    }

    @RequestMapping("/user+{id}")
    public String getUserById(@PathVariable("id") String id,ModelMap modelMap){
        UserBean userBean = userService.getUserById(id);
        List<UserImgBean> listUserImgBean = userService.getUserImgsById(id);
        modelMap.addAttribute("user",userBean);
        modelMap.addAttribute("userImgsList",listUserImgBean);
        return "userInfo";
    }

    @RequestMapping("/modifyUser")
    @ResponseBody
    public Map updateUser(UserBean userBean){
        int flag = userService.updateUser(userBean);
        Map<String,Object> map = new HashMap<>();
        if(flag == 1){
            map.put("msg","修改用户信息成功");
            return map;
        }else {
            map.put("msg","修改用户信息失败");
            return map;
        }
    }

    @RequestMapping(value = "/delUserImg")
    @ResponseBody
    public Map delUserImg(@RequestParam("id") String id){
        int flag = userService.delUserImg(id);
        Map<String,Object> mapMsg = new HashMap<>();
        if(flag == 1){
            mapMsg.put("msg","修改用户信息成功");
            return mapMsg;
        }else {
            mapMsg.put("msg","修改用户信息失败");
            return mapMsg;
        }
    }
}
